﻿//
// (C) Copyright 2009 Irantha Suwandarathna (iranthas@hotmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EffiProz.Core.Lib;
using EffiProz.Core.DataTypes;
using EffiProz.Core.Indexes;
using EffiProz.Core.Errors;
using EffiProz.Core.Persist;

namespace EffiProz.Core
{
    public class ExpressionOp : Expression
    {
        /**
    * Creates a binary operation expression
    */
        public ExpressionOp(int type, Expression left, Expression right)
            : base(type)
        {

            nodes = new Expression[BINARY];
            nodes[LEFT] = left;
            nodes[RIGHT] = right;

            switch (opType)
            {

                case OpTypes.ALTERNATIVE:
                case OpTypes.CASEWHEN:
                case OpTypes.LIMIT:
                case OpTypes.ZONE_MODIFIER:
                    return;

                default:
                    throw Error.runtimeError(ErrorCode.U_S0500, "ExpressionOp");
            }
        }

        /**
         * creates a CAST expression
         */
        public ExpressionOp(Expression e, SqlType dataType) :
            base(OpTypes.CAST)
        {

            nodes = new Expression[UNARY];
            nodes[LEFT] = e;
            this.dataType = dataType;
            this.alias = e.alias;
        }

        /**
         * creates a special conversion for time / timestamp comparison
         */
        public ExpressionOp(Expression e)
            : base(e.dataType.isDateTimeTypeWithZone() ? OpTypes.CAST
                      : OpTypes.ZONE_MODIFIER)
        {

            switch (e.dataType.typeCode)
            {

                case Types.SQL_TIME_WITH_TIME_ZONE:
                    nodes = new Expression[UNARY];
                    nodes[LEFT] = new ExpressionOp(OpTypes.ZONE_MODIFIER, e, null);
                    nodes[LEFT].dataType = e.dataType;
                    dataType = DateTimeType.getDateTimeType(Types.SQL_TIME,
                            e.dataType.scale);
                    break;

                case Types.SQL_TIMESTAMP_WITH_TIME_ZONE:
                    nodes = new Expression[UNARY];
                    nodes[LEFT] = new ExpressionOp(OpTypes.ZONE_MODIFIER, e, null);
                    nodes[LEFT].dataType = e.dataType;
                    dataType = DateTimeType.getDateTimeType(Types.SQL_TIMESTAMP,
                            e.dataType.scale);
                    break;

                case Types.SQL_TIME:
                    nodes = new Expression[BINARY];
                    nodes[LEFT] = e;
                    nodes[LEFT].dataType = e.dataType;
                    dataType =
                        DateTimeType.getDateTimeType(Types.SQL_TIME_WITH_TIME_ZONE,
                                                     e.dataType.scale);
                    break;

                case Types.SQL_TIMESTAMP:
                    nodes = new Expression[BINARY];
                    nodes[LEFT] = e;
                    nodes[LEFT].dataType = e.dataType;
                    dataType = DateTimeType.getDateTimeType(
                        Types.SQL_TIMESTAMP_WITH_TIME_ZONE, e.dataType.scale);
                    break;

                default:
                    throw Error.runtimeError(ErrorCode.U_S0500, "ExpressionOp");
            }

            this.alias = e.alias;
        }

        public static Expression getCastExpression(Session session, Expression e,
                                            SqlType dataType)
        {

            if (e.getType() == OpTypes.VALUE)
            {
                Object value = dataType.castToType(session, e.getValue(session),
                                                   e.getDataType());

                return new ExpressionValue(value, dataType);
            }

            return new ExpressionOp(e, dataType);
        }

        public override String getSQL()
        {

            StringBuilder sb = new StringBuilder(64);
            String left = getContextSQL(nodes.Length > 0 ? nodes[LEFT]
                                                                : null);
            String right = getContextSQL(nodes.Length > 1 ? nodes[RIGHT]
                                                                : null);

            switch (opType)
            {

                case OpTypes.VALUE:
                    if (valueData == null)
                    {
                        return Tokens.T_NULL;
                    }

                    if (dataType == null)
                    {
                        throw Error.runtimeError(ErrorCode.U_S0500,
                                                 "ExpressionOp");
                    }

                    return dataType.convertToSQLString(valueData);

                case OpTypes.CAST:
                    sb.Append(' ').Append(Tokens.T_CAST).Append('(');
                    sb.Append(left).Append(' ').Append(Tokens.T_AS).Append(' ');
                    sb.Append(dataType.getTypeDefinition());
                    sb.Append(')');

                    return sb.ToString();

                case OpTypes.CASEWHEN:
                    sb.Append(' ').Append(Tokens.T_CASEWHEN).Append('(');
                    sb.Append(left).Append(',').Append(right).Append(')');

                    return sb.ToString();

                case OpTypes.ALTERNATIVE:
                    sb.Append(left).Append(',').Append(right);

                    return sb.ToString();

                case OpTypes.LIMIT:
                    sb.Append(' ').Append(Tokens.T_OFFSET).Append(' ');
                    sb.Append(left).Append(' ');
                    sb.Append(Tokens.T_FETCH).Append(' ').Append(Tokens.T_FIRST);
                    sb.Append(right).Append(' ').Append(right).Append(' ');
                    sb.Append(Tokens.T_ROWS).Append(' ').Append(Tokens.T_ONLY);
                    sb.Append(' ');
                    break;

                case OpTypes.ZONE_MODIFIER:
                    sb.Append(left).Append(' ').Append(Tokens.T_AT).Append(' ');

                    if (nodes[RIGHT] == null)
                    {
                        sb.Append(Tokens.T_LOCAL).Append(' ');

                        break;
                    }

                    sb.Append(right);
                    break;

                default:
                    throw Error.runtimeError(ErrorCode.U_S0500, "ExpressionOp");
            }

            return sb.ToString();
        }

        public override String describe(Session session, int blanks)
        {

            StringBuilder sb = new StringBuilder(64);

            sb.Append('\n');

            for (int i = 0; i < blanks; i++)
            {
                sb.Append(' ');
            }

            switch (opType)
            {

                case OpTypes.VALUE:
                    sb.Append("VALUE = ").Append(valueData);
                    sb.Append(", TYPE = ").Append(dataType.getNameString());

                    return sb.ToString();

                case OpTypes.TABLE:
                    sb.Append("VALUELIST ");

                    for (int i = 0; i < nodes.Length; i++)
                    {
                        sb.Append(nodes[i].describe(session, blanks + 1));
                        sb.Append(' ');
                    }
                    break;

                case OpTypes.CAST:
                    sb.Append("CAST ");
                    sb.Append(dataType.getTypeDefinition());
                    sb.Append(' ');
                    break;

                case OpTypes.CASEWHEN:
                    sb.Append("CASEWHEN ");
                    break;
            }

            if (nodes[LEFT] != null)
            {
                sb.Append(" arg_left=[");
                sb.Append(nodes[LEFT].describe(session, blanks + 1));
                sb.Append(']');
            }

            if (nodes[RIGHT] != null)
            {
                sb.Append(" arg_right=[");
                sb.Append(nodes[RIGHT].describe(session, blanks + 1));
                sb.Append(']');
            }

            return sb.ToString();
        }

        public override EfzList resolveColumnReferences(RangeVariable[] rangeVarArray,
                int rangeCount, EfzList unresolvedSet, bool acceptsSequences)
        {

            if (opType == OpTypes.VALUE)
            {
                return unresolvedSet;
            }

            switch (opType)
            {

                case OpTypes.CASEWHEN:
                    acceptsSequences = false;
                    break;
            }

            for (int i = 0; i < nodes.Length; i++)
            {
                if (nodes[i] == null)
                {
                    continue;
                }

                unresolvedSet = nodes[i].resolveColumnReferences(rangeVarArray,
                        rangeCount, unresolvedSet, acceptsSequences);
            }

            return unresolvedSet;
        }

        public override void resolveTypes(Session session, Expression parent)
        {

            for (int i = 0; i < nodes.Length; i++)
            {
                if (nodes[i] != null)
                {
                    nodes[i].resolveTypes(session, this);
                }
            }

            switch (opType)
            {

                case OpTypes.VALUE:
                    break;

                case OpTypes.CAST:
                    {
                        SqlType type = nodes[LEFT].dataType;

                        if (type != null && !dataType.canConvertFrom(type))
                        {
                            throw Error.error(ErrorCode.X_42561);
                        }

                        if (nodes[LEFT].opType == OpTypes.VALUE)
                        {
                            setAsConstantValue(session);

                            break;
                        }

                        break;
                    }
                case OpTypes.ZONE_MODIFIER:
                    if (nodes[LEFT].dataType == null)
                    {
                        throw Error.error(ErrorCode.X_42567);
                    }

                    if (nodes[RIGHT] != null)
                    {
                        if (nodes[RIGHT].dataType == null)
                        {
                            nodes[RIGHT].dataType =
                                SqlType.SQL_INTERVAL_HOUR_TO_MINUTE;
                        }

                        if (nodes[RIGHT].dataType.typeCode
                                != Types.SQL_INTERVAL_HOUR_TO_MINUTE)
                        {
                            throw Error.error(ErrorCode.X_42565);
                        }
                    }

                    switch (nodes[LEFT].dataType.typeCode)
                    {

                        case Types.SQL_TIME:
                            dataType = DateTimeType.getDateTimeType(
                                Types.SQL_TIME_WITH_TIME_ZONE,
                                nodes[LEFT].dataType.scale);
                            break;

                        case Types.SQL_TIMESTAMP:
                            dataType = DateTimeType.getDateTimeType(
                                Types.SQL_TIMESTAMP_WITH_TIME_ZONE,
                                nodes[LEFT].dataType.scale);
                            break;

                        case Types.SQL_TIMESTAMP_WITH_TIME_ZONE:
                        case Types.SQL_TIME_WITH_TIME_ZONE:
                            dataType = nodes[LEFT].dataType;
                            break;

                        default:
                            throw Error.error(ErrorCode.X_42565);
                    }

                    // no constant optimisation as value dependent on session zone
                    break;

                case OpTypes.CASEWHEN:

                    // We use CASEWHEN as parent type.
                    // In the parent, left node is the condition, and right node is
                    // the leaf, tagged as type ALTERNATIVE; its left node is
                    // case 1 (how to get the value when the condition in
                    // the parent evaluates to true), while its right node is case 2
                    // (how to get the value when the condition in
                    // the parent evaluates to false).
                    resolveTypesForCaseWhen(session);
                    break;

                case OpTypes.ALTERNATIVE:
                    break;

                default:
                    throw Error.runtimeError(ErrorCode.U_S0500, "ExpressionOp");
            }
        }

        /**
         * For CASE WHEN and its special cases section 9.3 of the SQL standard
         * on type aggregation is implemented.
         */
        void resolveTypesForCaseWhen(Session session)
        {

            if (dataType != null)
            {
                return;
            }

            Expression expr = this;

            while (expr.opType == OpTypes.CASEWHEN)
            {
                expr.nodes[LEFT].resolveTypes(session, expr);

                if (expr.nodes[LEFT]._isParam)
                {
                    expr.nodes[LEFT].dataType = SqlType.SQL_BOOLEAN;
                }

                expr.nodes[RIGHT].nodes[LEFT].resolveTypes(session, nodes[RIGHT]);
                expr.nodes[RIGHT].nodes[RIGHT].resolveTypes(session, nodes[RIGHT]);

                expr = expr.nodes[RIGHT].nodes[RIGHT];
            }

            expr = this;

            while (expr.opType == OpTypes.CASEWHEN)
            {
                dataType =
                    SqlType.getAggregateType(expr.nodes[RIGHT].nodes[LEFT].dataType,
                                          dataType);
                dataType =
                    SqlType.getAggregateType(expr.nodes[RIGHT].nodes[RIGHT].dataType,
                                          dataType);
                expr = expr.nodes[RIGHT].nodes[RIGHT];
            }

            expr = this;

            while (expr.opType == OpTypes.CASEWHEN)
            {
                if (expr.nodes[RIGHT].nodes[LEFT].dataType == null)
                {
                    expr.nodes[RIGHT].nodes[LEFT].dataType = dataType;
                }

                if (expr.nodes[RIGHT].nodes[RIGHT].dataType == null)
                {
                    expr.nodes[RIGHT].nodes[RIGHT].dataType = dataType;
                }

                if (expr.nodes[RIGHT].dataType == null)
                {
                    expr.nodes[RIGHT].dataType = dataType;
                }

                expr = expr.nodes[RIGHT].nodes[RIGHT];
            }

            if (dataType == null)
            {
                throw Error.error(ErrorCode.X_42567);
            }
        }

        public override Object getValue(Session session)
        {

            switch (opType)
            {

                case OpTypes.VALUE:
                    return valueData;

                case OpTypes.SIMPLE_COLUMN:
                    {
                        Object[] data =
                            (Object[])session.sessionContext
                                .rangeIterators[rangePosition].getCurrent();

                        return data[columnIndex];
                    }
                case OpTypes.ORDER_BY:
                    return nodes[LEFT].getValue(session);

                case OpTypes.CAST:
                    {
                        Object value =
                            dataType.castToType(session,
                                                nodes[LEFT].getValue(session),
                                                nodes[LEFT].dataType);

                        if (dataType.userTypeModifier != null)
                        {
                            Constraint[] constraints =
                                dataType.userTypeModifier.getConstraints();

                            for (int i = 0; i < constraints.Length; i++)
                            {
                                constraints[i].checkCheckConstraint(session, null,
                                                                    value);
                            }
                        }

                        return value;
                    }
                case OpTypes.CASEWHEN:
                    {
                        Boolean? result = (Boolean?)nodes[LEFT].getValue(session);

                        if (true.Equals(result))
                        {
                            return nodes[RIGHT].nodes[LEFT].getValue(session,
                                    dataType);
                        }
                        else
                        {
                            return nodes[RIGHT].nodes[RIGHT].getValue(session,
                                    dataType);
                        }
                    }
                case OpTypes.ZONE_MODIFIER:
                    {
                        Object leftValue = nodes[LEFT].getValue(session);
                        Object rightValue = nodes[RIGHT] == null ? null
                                                                 : nodes[RIGHT]
                                                                     .getValue(
                                                                         session);

                        if (leftValue == null)
                        {
                            return null;
                        }

                        if (nodes[RIGHT] != null && rightValue == null)
                        {
                            return null;
                        }

                        long zoneSeconds = nodes[RIGHT] == null
                                           ? session.getZoneSeconds()
                                           : ((IntervalType)nodes[RIGHT].dataType)
                                               .getSeconds(rightValue);

                        return ((DateTimeType)dataType).changeZone(leftValue,
                                nodes[LEFT].dataType, (int)zoneSeconds,
                                session.getZoneSeconds());
                    }
                default:
                    throw Error.runtimeError(ErrorCode.U_S0500, "ExpressionOp");
            }
        }
    }
}
